package cn.alpha.intell.rbtlib.wifi.utils;


import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.wifi.SupplicantState;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.util.Log;

import java.util.List;

import cn.alpha.intell.rbtlib.utils.LogTool;
import cn.alpha.intell.rbtlib.utils.ReflectUtil;

import static android.net.wifi.WifiManager.EXTRA_NEW_STATE;

public class WifiConnector {
    private static final String TAG = "WifiConnector";
    private static final int WIFI_CONNECT_TIMEOUT = 10; //连接WIFI的超时时间
    private Context mContext;
    private WifiManager mWifiManager;
    private WiFiConncetReceiver mWifiConnectReceiver;
    private WifiConnectListener mWifiConnectListener;
    //private boolean mIsConnnected = false;
    private int mNetworkID = -1;

    public WifiConnector(Context context, WifiConnectListener listener) {
        mContext = context;
        //mLock = new ReentrantLock();
        //mCondition = mLock.newCondition();
        mWifiManager = (WifiManager) mContext.getSystemService(Context.WIFI_SERVICE);
        mWifiConnectReceiver = new WiFiConncetReceiver();
        mWifiConnectListener = listener;
    }

    public void connect(final String ssid, final String password, final WifiCipherType mode) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                //如果WIFI没有打开，则打开WIFI
                if (!mWifiManager.isWifiEnabled()) {
                    mWifiManager.setWifiEnabled(true);
                }
                //注册连接结果监听对象
                // mContext.registerReceiver(mWifiConnectReceiver, new IntentFilter(WifiManager.SUPPLICANT_STATE_CHANGED_ACTION));
                //连接指定SSID
                if (!onConnect(ssid, password, mode)) {
                    mWifiConnectListener.OnWifiConnectCompleted(false);
                } else {
                    mWifiConnectListener.OnWifiConnectCompleted(true);
                }
                //删除注册的监听类对象
                // if(mWifiConnectReceiver!=null)
                // mContext.unregisterReceiver(mWifiConnectReceiver);
            }
        }).start();
    }

    public void connect(final int networkID) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                //如果WIFI没有打开，则打开WIFI
                if (!mWifiManager.isWifiEnabled()) {
                    mWifiManager.setWifiEnabled(true);
                }
                //注册连接结果监听对象
                //mContext.registerReceiver(mWifiConnectReceiver, new IntentFilter(WifiManager.SUPPLICANT_STATE_CHANGED_ACTION));
                //连接指定SSID
                if (!onConnect(networkID)) {
                    mWifiConnectListener.OnWifiConnectCompleted(false);
                } else {
                    mWifiConnectListener.OnWifiConnectCompleted(true);
                }
                //删除注册的监听类对象
                //if(mWifiConnectReceiver!=null)
                //    mContext.unregisterReceiver(mWifiConnectReceiver);
            }
        }).start();
    }

    protected boolean onConnect(String ssid, String password, WifiCipherType mode) {
        boolean isoperSuccess = false;
        //添加新的网络配置
        WifiConfiguration cfg = createWifiConfig(ssid, password, mode);

        if (cfg != null) {
            //添加网络配置
            mNetworkID = mWifiManager.addNetwork(cfg);
            //连接该网络
            if (mNetworkID != -1) {
                if (mWifiManager.enableNetwork(mNetworkID, true)) {
                    isoperSuccess = true;
                } else {
                    isoperSuccess = false;
                }
            }
        }
        return isoperSuccess;
    }

    protected boolean onConnect(int networkID) {
        mNetworkID = networkID;
        boolean isOperSuccess;
        //mLock.lock();
        //mIsConnnected = false;
        //连接该网络
        if (mWifiManager.enableNetwork(mNetworkID, true)) {
            // mLock.unlock();
            isOperSuccess = true;
        } else {
            isOperSuccess = false;
        }
        return isOperSuccess;
    }

    public void removeWIFINetWorkID() {
        if (mNetworkID != -1) {
            mWifiManager.removeNetwork(mNetworkID);
        }
    }

    public void removeWIFINetWorkID(int networkID) {
        if (mNetworkID != -1) {
            mWifiManager.removeNetwork(networkID);
        }
    }

    public void disableWIFINetWorkID() {
        if (mNetworkID != -1) {
            mWifiManager.disableNetwork(mNetworkID);
        }

    }

    public void disableWIFINetWorkID(int networkID) {
        if (mNetworkID != -1) {
            mWifiManager.disableNetwork(mNetworkID);
        }
    }

    public WifiInfo getConnectNetworkInfo() {

        return mWifiManager.getConnectionInfo();

    }

    public void removeWiFiConfig() {
        List<WifiConfiguration> wifiConfigurations = mWifiManager.getConfiguredNetworks();
        if (wifiConfigurations != null) {
            for (WifiConfiguration wifiConfiguration : wifiConfigurations) {
                Log.d(TAG, wifiConfiguration.SSID);
                mWifiManager.removeNetwork(wifiConfiguration.networkId);
                mWifiManager.saveConfiguration();
            }
        }
    }

    public void removeWiFiConfigBySSID(String ssid) {
        List<WifiConfiguration> wifiConfigurations = mWifiManager.getConfiguredNetworks();
        if (wifiConfigurations != null) {
            for (WifiConfiguration wifiConfiguration : wifiConfigurations) {
                Log.d(TAG, wifiConfiguration.SSID);
                if (wifiConfiguration.SSID.replace("\"", "").equals(ssid.replace("\"", ""))) {
                  boolean operResult =  mWifiManager.removeNetwork(wifiConfiguration.networkId);
                    Log.d(TAG,"operResult ==" +operResult);
                    mWifiManager.saveConfiguration();
                }
            }
        }

    }

    private WifiConfiguration createWifiConfig(String SSID, String Password,
                                               WifiCipherType Type) {
        WifiConfiguration config = new WifiConfiguration();

        config.allowedAuthAlgorithms.clear();
        config.allowedGroupCiphers.clear();
        config.allowedKeyManagement.clear();
        config.allowedPairwiseCiphers.clear();
        config.allowedProtocols.clear();

        config.SSID = "\"" + SSID + "\"";

        if (Type == WifiCipherType.WIFICIPHER_NOPASS) {
           // config.wepKeys[0] = "";
            config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
            config.wepTxKeyIndex = 0;
            config.hiddenSSID = true;
        }
        else if (Type == WifiCipherType.WIFICIPHER_WEP) {
            config.preSharedKey = "\"" + Password + "\"";
            config.hiddenSSID = true;
            config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.SHARED);
            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104);
            config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
            config.wepTxKeyIndex = 0;
        }
        else if (Type == WifiCipherType.WIFICIPHER_WPA) {
            config.preSharedKey = "\"" + Password + "\"";
            config.hiddenSSID = true;
            config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
            config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);

            config.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
            config.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);

            config.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
            config.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
            config.status = WifiConfiguration.Status.ENABLED;
        } else {
            return null;
        }
        return config;
    }

    public List<WifiConfiguration> getWifiConfiguration() {
        return mWifiManager.getConfiguredNetworks();
    }

    /**
     * 此wifi热点是否framework自动添加
     * 参考源码: WifiSettings
     * @param configuration
     * @return
     */
    public static boolean isSysAutoAdd(WifiConfiguration configuration) {
        if (configuration == null) {
            return false;
        }
        boolean selfAdded = (boolean)ReflectUtil.getFieldValue(configuration, "selfAdded");
        int numAssociation = (int)ReflectUtil.getFieldValue(configuration, "numAssociation");
        LogTool.d(TAG, "isSysAutoAdd selfAdded:"+selfAdded+" numAssociation:"+numAssociation);
        if (selfAdded && numAssociation == 0) {
            return true;
        }
        return false;
    }

    //网络加密模式
    public enum WifiCipherType {
        WIFICIPHER_WEP, WIFICIPHER_WPA, WIFICIPHER_NOPASS, WIFICIPHER_INVALID
    }

    //通知连接结果的监听接口
    public interface WifiConnectListener {
        public void OnWifiConnectCompleted(boolean isConnected);
    }

    //监听系统的WIFI连接消息
    protected class WiFiConncetReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (!WifiManager.SUPPLICANT_STATE_CHANGED_ACTION.equals(intent.getAction())) {
                return;
            }
            //mLock.lock();
            SupplicantState supplicantState = intent.getParcelableExtra(EXTRA_NEW_STATE);

            WifiInfo info = mWifiManager.getConnectionInfo();

            if (info.getNetworkId() == mNetworkID && supplicantState == SupplicantState.COMPLETED) {
                //mIsConnnected = true;
                // mCondition.signalAll();
            }
            //mLock.unlock();
        }
    }
}